package com.medplus.hubdirect.web;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.medplus.hubdirect.dao.UserEndPointDAO;
import com.medplus.hubdirect.model.User;
import com.medplus.hubdirect.model.UserEndPoint;

/**
 * Handles requests for the application welcome page.
 */
@Controller
@SessionAttributes("userEndPoint")
public class EndPointController {
	
	@Autowired
	private UserEndPointDAO userEndPointDAO;
	
	private Logger logger = org.slf4j.LoggerFactory.getLogger(EndPointController.class);

	public EndPointController() {
	}
	

	@RequestMapping(value="/user/{userId}/endpoint/new", method=RequestMethod.GET)
	public String setupNewEndPoint(@PathVariable("userId") int userId, Model model) {
		User user = userEndPointDAO.findUserById(userId);
		UserEndPoint ep = new UserEndPoint();
		ep.setUserName(user.getUserName());
		ep.setUser(user);
		model.addAttribute("userEndPoint", ep);
		return "endpoint/createPage"; 
	}
	
	@RequestMapping(value="/user/{userId}/endpoint/new", method=RequestMethod.POST)
	public String create(@Valid UserEndPoint userEndPoint, BindingResult result, @PathVariable("userId") int userId, SessionStatus status) {
		// result has objectName always points to "endPoint", no matter what I actually set.
		if (result.hasErrors()) {			
			// how to get model?  		
			return "/endpoint/createPage";
		}
		
		userEndPointDAO.addEndPointToUser(userEndPoint);
		
		// Clears @SessionAttributes
		status.setComplete();
		
		return "redirect:/user/" + userId; 
	}
	
}

/**

	public void testJPA() {
		User user = new User();
		user.setUserName("yzhou");

		Set<UserEndPoint> endpoints = new HashSet<UserEndPoint>();
		
		UserEndPoint pt1 = new UserEndPoint();
		pt1.setEndPoint("endpoint1");
		pt1.setUser(user);
		
		UserEndPoint pt2 = new UserEndPoint();
		pt2.setEndPoint("endpoint2");
		pt2.setUser(user);
		endpoints.add(pt1);
		endpoints.add(pt2);		
		
		user.setEndpoints(endpoints);
				
		userEndPointDAO.save(user);
				
		userEndPointDAO.deleteEndPointFromUser(pt1);

		UserEndPoint pt3 = new UserEndPoint();
		pt3.setEndPoint("endpoint3");
		pt3.setUserName(user.getUserName());

		userEndPointDAO.addEndPointToUser(pt3);
		
		userEndPointDAO.delete(user);		
	}
	
 */ 
